package jnpf.scheduletask.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jnpf.permission.OrganizeApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.entity.UserEntity;
import jnpf.task.entity.TaskEntity;
import jnpf.task.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class synUserHandler {
    @Autowired
    private UserApi userApi;
    @Autowired
    private TaskService taskService;
    @Autowired
    private OrganizeApi organizeApi;

    @XxlJob("synUserHandler")
    @Transactional
    public void defaultHandler() throws Exception {
        TaskEntity info = taskService.getInfo("625626000012621637");

        String url = info.getUrl();

        String   date1= DateUtil.format(new Date(),  "yyyy-MM-dd") ;
        String   date2= DateUtil.format(new Date(),  "yyyy-MM-dd") ;

        if(info.getParam2()!=null){
            date1=info.getParam2();
        }
        String  pageIndex="0";
        if(info.getParam3()!=null){
            pageIndex=info.getParam3();
        }
        url=url+"&pageIndex="+pageIndex;
        String body="{\n" +
                "    \"parseRef\":{\n" +
                "        \"parseRefDictField\":true,\n" +
                "        \"parseRefOrdinaryField\":true,\n" +
                "        \"parseRefReferenceField\":true,\n" +
                "        \"replaceRefDictValue\":true,\n" +
                "        \"replaceRefOrdinaryValue\":true,\n" +
                "        \"parseRefWithSuffix\":\"\"\n" +
                "    },\n" +
                "    \"args\": [\n" +
                "        {\n" +
                "            \"name\": \"M_DATA_STATE\",\n" +
                "            \"matchValues\": [\n" +
                "                \"0\",\n" +
                "                \"5\"\n" +
                "            ],\n" +
                "            \"matchType\": \"in\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"M_LAST_MODIFIED_AT\",\n" +
                "            \"matchValues\": [\n" +
                "                \""+date1+" 00:00:00\",\n" +
                "                \""+date2+" 23:59:59\"\n" +
                "            ],\n" +
                "            \"matchType\": \"between\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"sorts\":[\n" +
                "    ],\n" +
                "    \"criteria\":{\n" +
                "        \"children\":[\n" +
                "        ],\n" +
                "        \"matchType\":\"\"\n" +
                "    },\n" +
                "    \"desensitization\":true\n" +
                "}\n";

        String post = HttpRequest.post(url)
                .header(Header.USER_AGENT, "Hutool http")//头信息，多个头信息多次调用此方法即可
                .header("AppKey",info.getParam1())
                .body(body )
                .timeout(120000)//超时，毫秒
                .execute().body();


        XxlJobHelper.log("boday:[{}]",body);

        XxlJobHelper.log("请求返回的数据为：[{}]", post);

        // 对返回的数据进行解析

        JSONObject jsonObject= new JSONObject(post);

        JSONArray jsonArray= (JSONArray) jsonObject.get("content");

          Integer pagebunber= Integer.valueOf(pageIndex);

        if(CollectionUtil.isNotEmpty(jsonArray)) {
            pagebunber=pagebunber+1;
            info.setParam3(pagebunber.toString());

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String account = jsonObject1.getStr("job_number");
                String M_DATA_STATE = jsonObject1.getStr("M_DATA_STATE");
                if(!M_DATA_STATE.equals("5")){
                    //根据工号查询用户
                    UserEntity userEntity = userApi.getInfoByAccount(account);
                    if(userEntity==null){
                        UserEntity userEntity1 =new UserEntity();

                        userEntity1.setAccount(account);
                        userEntity1.setRealName(jsonObject1.getStr("name"));
                        userEntity1.setNickName(jsonObject1.getStr("name"));
                        userEntity1.setNameEn(jsonObject1.getStr("name_en"));
                        if(jsonObject1.getStr("gender")!=null ){
                            if(jsonObject1.getStr("gender").equals("男")){
                                userEntity1.setGender("0");
                            }
                            if(jsonObject1.getStr("gender").equals("女")){
                                userEntity1.setGender("1");
                            }
                            if(jsonObject1.getStr("gender").equals("保密")){
                                userEntity1.setGender("2");
                            }

                        }
                        userEntity1.setUserOid(jsonObject1.getStr("user_oid"));




                        //  enabledMark            <el-option label="启用" :value="1"></el-option>
                        //                <el-option label="禁用" :value="0"></el-option>
                        //                <el-option label="锁定" :value="2"></el-option>


                        JSONArray employee_tenure_infoArray = jsonObject1.getJSONArray("employee_tenure_info");
                       if(employee_tenure_infoArray!=null){
                           for (int k = 0; k < employee_tenure_infoArray.size(); k++) {
                               JSONObject jsonObject2 = employee_tenure_infoArray.getJSONObject(k);

                               if(jsonObject2!=null) {
                                   if (jsonObject2.getStr("employee_status") != null && (jsonObject2.getStr("employee_status").equals("12") ||
                                           jsonObject2.getStr("employee_status").equals("2") ||
                                           jsonObject2.getStr("employee_status").equals("3") ||
                                           jsonObject2.getStr("employee_status").equals("4") ||
                                           jsonObject2.getStr("employee_status").equals("5")
                                   )

                                   ) {
                                       userEntity1.setEnabledMark(1);
                                   } else {
                                       userEntity1.setEnabledMark(0);
                                   }

                                   String department_code = jsonObject2.getStr("   ");
                                   if (department_code != null) {
                                       OrganizeEntity organize = organizeApi.getInfoByCode(department_code, "0");
                                        if(organize!=null){
                                            XxlJobHelper.log("部门："+organize.getFullName());
                                            userEntity1.setOrganizeId(organize.getId());
                                        }

                                   }
                                   // 设置部门领导
                                   if (jsonObject2.getStr("emp_admin_oid") != null) {

                                       UserEntity userEntity2 = userApi.getInfoByUserOid(jsonObject2.getStr("emp_admin_oid"));
                                       if (userEntity2 != null) {
                                           userEntity1.setManagerId(userEntity2.getId());

                                       }


                                   }
                                   userEntity1.setEmail(jsonObject2.getStr("email"));


                               }




                            break;
                           }

                       }





                        Boolean aBoolean = userApi.create(userEntity1);
                        if(!aBoolean){
                            throw new Exception("插入失败");
                        }
                        XxlJobHelper.log("插入："+account);


                    }else {
                        userEntity.setRealName(jsonObject1.getStr("name"));
                        userEntity.setNickName(jsonObject1.getStr("name"));
                        userEntity.setNameEn(jsonObject1.getStr("name_en"));
                        if(jsonObject1.getStr("gender")!=null ){
                            if(jsonObject1.getStr("gender").equals("男")){
                                userEntity.setGender("0");
                            }
                            if(jsonObject1.getStr("gender").equals("女")){
                                userEntity.setGender("1");
                            }
                            if(jsonObject1.getStr("gender").equals("保密")){
                                userEntity.setGender("2");
                            }

                        }

                        userEntity.setUserOid(jsonObject1.getStr("user_oid"));




                        //  enabledMark            <el-option label="启用" :value="1"></el-option>
                        //                <el-option label="禁用" :value="0"></el-option>
                        //                <el-option label="锁定" :value="2"></el-option>


                        JSONArray employee_tenure_infoArray = jsonObject1.getJSONArray("employee_tenure_info");
                        for (int k = 0; k < employee_tenure_infoArray.size(); k++) {
                            JSONObject jsonObject2 = employee_tenure_infoArray.getJSONObject(k);


                            if(jsonObject2!=null) {

                                if (jsonObject2.getStr("employee_status") != null && (jsonObject2.getStr("employee_status").equals("12") ||
                                        jsonObject2.getStr("employee_status").equals("2") ||
                                        jsonObject2.getStr("employee_status").equals("3") ||
                                        jsonObject2.getStr("employee_status").equals("4") ||
                                        jsonObject2.getStr("employee_status").equals("5"))


                                ) {
                                    userEntity.setEnabledMark(1);
                                } else {
                                    userEntity.setEnabledMark(0);
                                }

                                String department_code = jsonObject2.getStr("department_code");
                                if (department_code != null) {
                                    OrganizeEntity organize = organizeApi.getInfoByCode(department_code, "0");
                                    if(organize!=null){
                                    XxlJobHelper.log("部门："+organize.getFullName());

                                    userEntity.setOrganizeId(organize.getId());
                                    }
                                }
                                // 设置部门领导
                                if (jsonObject2.getStr("emp_admin_oid") != null) {

                                    UserEntity userEntity2 = userApi.getInfoByUserOid(jsonObject2.getStr("emp_admin_oid"));
                                    if (userEntity2 != null) {
                                        userEntity.setManagerId(userEntity2.getId());

                                    }


                                }
                                userEntity.setEmail(jsonObject2.getStr("email"));


                            }
                            break;


                        }



                        Boolean update = userApi.update(userEntity.getId(), userEntity);

                        if(!update){
                            throw new Exception("更新失败");
                        }
                        XxlJobHelper.log("更新："+account);
                    }





                }



            }
        }else {
            info.setParam3("0");
        }

        taskService.update(info.getId(),info);



    }
}
